﻿using Microsoft.EntityFrameworkCore;

namespace SmartCommunity.Models
{
    public class DBInitializer
    {
        /// <summary>
        /// 自动创建数据库
        /// </summary>
        public static void EnsureDatabaseCreated(IServiceProvider serviceProvider, bool recreated = false)
        {
            using var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
            var ctx = scope.ServiceProvider.GetRequiredService<SCDBContext>();
            if (recreated) ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();
            EnsureSeedData(ctx);
        }

        /// <summary>
        /// 自动执行迁移
        /// </summary>
        public static void AutoMigrate(IServiceProvider serviceProvider)
        {
            using var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
            var ctx = scope.ServiceProvider.GetRequiredService<SCDBContext>();
            ctx.Database.Migrate();
        }

        public static void EnsureSeedData(SCDBContext ctx)
        {
            var admin = "SuperAdmin";
            if (ctx.Users.Any()) return;

            using var trans = ctx.Database.BeginTransaction();

            #region 菜单数据 
            var menuCommunity = CreateMenu(MenuType.Module, "社区管理", "/community", "community", "mdi-family-tree", 1);
            menuCommunity.Children = [
                CreateMenu(MenuType.Menu, "社区档案", "/community/community", "community:user", "mdi-city", 1),
                CreateMenu(MenuType.Menu, "小区档案", "/community/area", "community:area", "mdi-home-city", 2),
                CreateMenu(MenuType.Menu, "小区楼栋", "/community/building", "community:building", "mdi-office-building", 3),
                CreateMenu(MenuType.Menu, "房产资源", "/community/room", "community:person", "mdi-human-queue", 4),
            ];
            var menuOrder = CreateMenu(MenuType.Module, "工单管理", "/workorder", "community", "mdi-order-bool-descending-variant", 2);
            menuOrder.Children = [
                CreateMenu(MenuType.Menu, "工单录入", "/workorder/neworder", "workorder:neworder", "mdi-border-color", 1),
                CreateMenu(MenuType.Menu, "我的工单", "/workorder/myorder", "workorder:myorder", "mdi-reorder-vertical", 2),
                CreateMenu(MenuType.Menu, "工单统计", "/workorder/allorder", "workorder:allorder", "mdi-chart-bar", 3),
            ];
            var wuyeOrder = CreateMenu(MenuType.Module, "物业管理", "/property", "community", "mdi-family-tree", 3);
            wuyeOrder.Children = [
                CreateMenu(MenuType.Menu, "小区住户", "/property/persons", "community:user", "mdi-account-multiple", 1),
            ];

            var menuSys = CreateMenu(MenuType.Module, "系统管理", "/system", "system", "mdi-cog-outline", 4);
            menuSys.Children = [
                CreateMenu(MenuType.Menu, "用户管理", "/system/user", "system:user", "mdi-account-outline", 1),
                CreateMenu(MenuType.Menu, "角色管理", "/system/role", "system:role", "mdi-account-group-outline", 2),
                CreateMenu(MenuType.Menu, "菜单管理", "/system/menu", "system:menu", "mdi-menu", 3),
                CreateMenu(MenuType.Menu, "字典管理", "/system/dict", "system:dict", "mdi-book-outline", 5),
                CreateMenu(MenuType.Menu, "参数配置", "/system/config", "system:config", "mdi-square-edit-outline", 6),
            ];
            var menuMonitor = CreateMenu(MenuType.Module, "系统监控", "/monitor", "monitor", "mdi-monitor", 3);
            menuMonitor.Children = [
               CreateMenu(MenuType.Menu, "日志管理", "/monitor/log", "monitor:log", "mdi-database-cog-outline", 1),
            ];

            ctx.Menus.AddRange(menuCommunity, menuOrder, wuyeOrder, menuSys, menuMonitor);
            ctx.SaveChanges();
            foreach (var entity in ctx.Menus)
            {
                entity.CreatedBy = entity.UpdatedBy = "SuperAdmin";
                entity.CreatedTime = entity.UpdatedTime = DateTime.Parse("2024-07-05");
            }
            #endregion

            #region 角色数据
            var menus = ctx.Menus.ToList();
            var roleSuper = new RoleEntity()
            {
                RoleCode = admin,
                RoleName = "超级管理员",
                Remark = "超级管理员，拥有所有权限，系统内置，不允许编辑删除",
                Menus = menus
            };

            var roleAdmin = new RoleEntity()
            {
                RoleCode = "admin",
                RoleName = "系统管理员",
                Remark = "系统管理员，拥有所有权限。只有管理员可以创建社区",
                Menus = menus.Where(a => !a.Permission.StartsWith("monitor") && a.Permission != "system:menu").ToList()
            };

            var roleCommunity = new RoleEntity()
            {
                RoleCode = "community-admin",
                RoleName = "社区管理员",
                Remark = "社区管理员，可以对权限的社区进行所有操作",
                Menus = menus.Where(a => a.Permission.StartsWith("community")).ToList()
            };

            ctx.Roles.AddRange(roleSuper, roleAdmin, roleCommunity);
            ctx.SaveChanges();
            foreach (var entity in ctx.Roles)
            {
                entity.CreatedBy = entity.UpdatedBy = "admin";
                entity.CreatedTime = entity.UpdatedTime = DateTime.Parse("2024-07-05");
            }
            #endregion

            #region 用户数据
            var pwd = "123456";
            var avatar = "https://s2.loli.net/2022/04/07/gw1L2Z5sPtS8GIl.gif";
            ctx.Users.AddRange(
                new UserEntity() { Roles = [roleSuper], Username = "SuperAdmin", Password = "wjladmin", Nickname = "超级管理员", Cellphone = "16666666666", Gender = "O", Email = "wjlxxfn@gmail.com", Avatar = avatar },
                new UserEntity() { Roles = [roleAdmin], Username = "admin", Password = pwd, Nickname = "管理员", Cellphone = "18888888888", Gender = "O", Email = "wjlxxfn@gmail.com", Avatar = avatar }
            );
            ctx.SaveChanges();
            foreach (var entity in ctx.Users)
            {
                entity.CreatedBy = entity.UpdatedBy = "admin";
                entity.CreatedTime = entity.UpdatedTime = DateTime.Parse("2024-07-05");
            }
            #endregion

            #region 数据字典
            var blDict = new DictEntity() { DictType = "BuildingLevel", DictName = "楼宇层级", Remark = "1:主楼栋 2:单元楼" };
            blDict.DictItems = [
              new DictItemEntity(){DictCode="Main",DictValue="1",DictLabel="主楼宇",SortNo= 1},
                new DictItemEntity(){DictCode="Unit",DictValue="2",DictLabel="单元楼",SortNo= 2},
            ];
            var btDict = new DictEntity() { DictType = "BuildingType", DictName = "建筑类型", Remark = "别墅/高层/小高层/中高层" };
            btDict.DictItems = [
                new DictItemEntity(){DictCode="Senior",DictValue="1",DictLabel="别墅",SortNo= 1},
                new DictItemEntity(){DictCode="Lower",DictValue="2",DictLabel="小高层",SortNo= 2},
                new DictItemEntity(){DictCode="Middle",DictValue="3",DictLabel="中高层",SortNo= 3},
                new DictItemEntity(){DictCode="High",DictValue="4",DictLabel="高层",SortNo= 4},
            ];
            var buDict = new DictEntity() { DictType = "BuildingUsage", DictName = "建筑用途", Remark = "住宅/商用/商住两用" };
            buDict.DictItems = [
                new DictItemEntity(){DictCode="Family",DictValue="1",DictLabel="住宅",SortNo= 1},
                new DictItemEntity(){DictCode="Business",DictValue="2",DictLabel="商用",SortNo= 2},
                new DictItemEntity(){DictCode="Fixed",DictValue="3",DictLabel="商住两用",SortNo= 3},
            ];
            var bdDict = new DictEntity() { DictType = "BuildingDirection", DictName = "建筑朝向", Remark = "东南西北" };
            bdDict.DictItems = [
                new DictItemEntity(){DictCode="East",DictValue="1",DictLabel="东方",SortNo= 1},
                new DictItemEntity(){DictCode="South",DictValue="2",DictLabel="南方",SortNo= 2},
                new DictItemEntity(){DictCode="West",DictValue="3",DictLabel="西方",SortNo= 3},
                new DictItemEntity(){DictCode="North",DictValue="4",DictLabel="北方",SortNo= 4},
            ];


            var rsDict = new DictEntity() { DictType = "RoomState", DictName = "房间状态", Remark = "" };
            rsDict.DictItems = [
               new DictItemEntity(){DictCode="ZaiShou",DictValue="1",DictLabel="在售",SortNo= 1},
               new DictItemEntity(){DictCode="YiShou",DictValue="2",DictLabel="已售",SortNo= 2},
            ];
            var rtDict = new DictEntity() { DictType = "RoomType", DictName = "房间户型", Remark = "" };
            rtDict.DictItems = [
                new DictItemEntity(){DictCode="YiShi",DictValue="1",DictLabel="一室",SortNo= 1},
                new DictItemEntity(){DictCode="YiShiYiTing",DictValue="2",DictLabel="一室一厅",SortNo= 2},
            ];
            var ruDict = new DictEntity() { DictType = "RoomUsage", DictName = "房间用途", Remark = "" };
            ruDict.DictItems = [
               new DictItemEntity(){DictCode="ZhuZhai",DictValue="1",DictLabel="住宅",SortNo= 1},
                new DictItemEntity(){DictCode="ShangPu",DictValue="2",DictLabel="商铺",SortNo= 2},
            ];
            var rdDict = new DictEntity() { DictType = "RoomDeco", DictName = "装饰情况 ", Remark = "" };
            rdDict.DictItems = [
                new DictItemEntity(){DictCode="MaoPi",DictValue="1",DictLabel="毛坯",SortNo= 1},
                new DictItemEntity(){DictCode="JianDanZhuangXiu",DictValue="2",DictLabel="简单装修",SortNo= 2},
                new DictItemEntity(){DictCode="JingZhuangXiu",DictValue="3",DictLabel="精装修",SortNo= 3},
            ];
            var gdDict = new DictEntity() { DictType = "WorkOrderType", DictName = "工单类型 ", Remark = "" };
            gdDict.DictItems = [
                new DictItemEntity(){DictCode="TouSuJianyi",DictValue="1",DictLabel="投诉建议",SortNo= 1},
                new DictItemEntity(){DictCode="FaLvYuanZhu",DictValue="2",DictLabel="法律援助",SortNo= 2},
                new DictItemEntity(){DictCode="SheQuJianYi",DictValue="3",DictLabel="社区建议",SortNo= 3},
                new DictItemEntity(){DictCode="MinZhengJiuZHu",DictValue="4",DictLabel="民政救助",SortNo= 4},
                new DictItemEntity(){DictCode="GongGongAnQuan",DictValue="5",DictLabel="公共安全",SortNo= 5},
                new DictItemEntity(){DictCode="JinJiQiuZhu",DictValue="6",DictLabel="紧急求助",SortNo= 6},
                new DictItemEntity(){DictCode="HuanJingWeiSheng",DictValue="7",DictLabel="环境卫生",SortNo= 7},
                new DictItemEntity(){DictCode="WeiXiuFuWu",DictValue="8",DictLabel="维修服务",SortNo= 8},
                new DictItemEntity(){DictCode="BianMinFuWu",DictValue="9",DictLabel="便民服务",SortNo= 9},
                new DictItemEntity(){DictCode="QiTa",DictValue="9",DictLabel="其他",SortNo= 10},
            ];
            var gdsDict = new DictEntity() { DictType = "WorkOrderStatus", DictName = "工单状态", Remark = "" };
            gdsDict.DictItems = [
                new DictItemEntity(){DictCode="XinLvRu",DictValue="0",DictLabel="新录入",SortNo= 1},
                new DictItemEntity(){DictCode="YiFenPei",DictValue="1",DictLabel="已分配",SortNo= 2},
                new DictItemEntity(){DictCode="ChuLiZhong",DictValue="2",DictLabel="处理中",SortNo= 3},
                new DictItemEntity(){DictCode="ChuLiWanCheng",DictValue="3",DictLabel="处理完成",SortNo= 4},
            ];
            ctx.Dicts.AddRange(blDict, btDict, bdDict, buDict, rsDict, rtDict, rdDict, ruDict,gdDict,gdsDict);
            ctx.SaveChanges();
            #endregion

            #region 社区
            var objCommunity = new CommunityEntity()
            {
                CommunityName = "平邑街道汇金湾社区",
                ManagerName = "杨学海",
                ManagerTel = "17852276001",
                CreatedDate = DateOnly.FromDateTime(DateTime.Parse("2022-12-04")),
                Remark = "平邑街道汇金湾社区下辖9个商业小区，服务管理12000余人，汇金湾社区本着“幸福汇金湾  服务在身边”的服务理念，24小时为居民提供服务，解决群众急难愁盼相关问题。"
            };
            objCommunity.Areas.Add(new AreaEntity()
            {
                AreaName = "东方佳园",
                BuildArea = 9,
                PlantArea = 1,
                TotalArea = 10,
                CommunityName = "平邑街道汇金湾社区",
                AreaAddr = "东方佳园",
                Remark = "东方佳园"
            });
            objCommunity.Areas.Add(new AreaEntity()
            {
                AreaName = "荣达花园",
                BuildArea = 9,
                PlantArea = 1,
                TotalArea = 10,
                CommunityName = "平邑街道汇金湾社区",
                AreaAddr = "荣达花园",
                Remark = "荣达花园"
            });
            ctx.Communities.Add(objCommunity);
            ctx.SaveChanges();
            foreach (var entity in ctx.Communities.Include(a => a.Areas))
            {
                entity.CreatedBy = entity.UpdatedBy = "admin";
                entity.CreatedTime = entity.UpdatedTime = DateTime.Parse("2024-07-05");
                foreach (var area in entity.Areas)
                {
                    area.CreatedBy = area.UpdatedBy = "admin";
                    area.CreatedTime = area.UpdatedTime = DateTime.Parse("2024-07-05");
                }
            }
            #endregion

            ctx.SaveChanges();
            trans.Commit();
        }

        private static MenuEntity CreateMenu(MenuType type, string name, string path, string permission, string icon, int sortNo)
        {
            var menu = new MenuEntity()
            {
                MenuType = type,
                MenuName = name,
                MenuPath = path,
                Permission = permission,
                Icon = icon,
                SortNo = sortNo,
                Remark = ""
            };
            return menu;
        }
    }
}